﻿//初始化下拉框的数据
var jiancebiaozhun_list = ['NB/T 47013.2-2015', 'GB/T 3323-2005', 'DL/T 821-2017', 'GB/T 12605-2008', 'SY/T 4109-2013'];
var rechuli_list = ['无', '热处理后'];
var guige_list = ["Ф32×3.5", "Ф38×3.5", "Ф45×4.0", "Ф57×4.0", "Ф60×4.5", "Ф76×4.5",
    "Ф89×5.0", "Ф108×5.0", "Ф114×6.0", "Ф133×6.0", "Ф159×6.0", "Ф168×6.0", "Ф219×6.0",
    "Ф273×8.0", "Ф325×8.0", "Ф377×8.0", "Ф426×10.0", "Ф530×12.0", "Ф630×12.0", "Ф720×14.0",
    "Ф820×14.0", "Ф920×16.0", "Ф1020×16.0"];
var pokouxingshi_list = ["V", "X", "I", "U", "W", "V"];
var caizhi_list = ["Q235", "Q345", "16MnR", "1Cr18Ni9", "1Cr18Ni9Ti"];
var hanjiefangfa_list = ["手工电弧焊SMAW", "埋弧自动焊SAW", "钨极氩弧焊TIG", "钨极气体保护电弧焊GTAW", "二氧化碳气体保护电弧焊FCAW"];
var jiancefangfa_list = ["射线检测（RT）", "超声检测（UT）", "磁粉检测（MT）", "渗透检测（PT）",
    "射线检测（CR）", "射线检测（DR）", "衍射时差法超声检测（TOFD）", "相控阵超声检测（PAUT）"];
var jiancebuwei_list = ["焊接接头", "焊缝", "焊缝及热影响区"];
var hegejibie_list = ["Ⅰ", "Ⅱ", "Ⅲ"];
var shexian_list = ["X射线", "γ射线"];
var bili_list = ["5%", "20%", "50%", "100%"];
var projectID = GetQueryString("id");

for (let i = 0; i < jiancebiaozhun_list.length; i++) {
    document.getElementById('task_standard').options.add(new Option(jiancebiaozhun_list[i]));
}
for (let i = 0; i < rechuli_list.length; i++) {
    document.getElementById('task_heat').options.add(new Option(rechuli_list[i]));
}
for (let i = 0; i < shexian_list.length; i++) {
    document.getElementById('task_type').options.add(new Option(shexian_list[i]));
}
for (let i = 0; i < jiancebuwei_list.length; i++) {
    document.getElementById('task_position').options.add(new Option(jiancebuwei_list[i]));
}
// for (var i = 0; i < pokouxingshi_list.length; i++) {
//     document.getElementById('pokouxingshi').options.add(new Option(pokouxingshi_list[i]))
// }

//从数据库中拿到 项目名称
var projectName = '';
$.ajax({
    url: '/pj/checkDepute',
    type: 'post',
    data: { 'requestType': 'initBaseData', 'pj_id': projectID },
    async: false,
    success: function (data, status) {
        if (status === 'success') {
            projectName = data[0].pj_name;
            document.getElementById('task_pname').value = projectName;
            document.getElementById('task_company').value = data[0].pj_company;
        }
    },
    error: function (data, status) {
        if (status === 'error') {
            alert("会不会使啊！");
        }
    }
});
/*
郑旭实现
以下实现动态列表功能，包括动态添加一行，自动复制上一行的值，删除
 */
var table = [document.getElementById("table0")];//指向需要添加的表
var type = [[0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1]];//数据类型，0为文本，1为选项框
var selection = [[[], [], [], bili_list, [], [], guige_list, caizhi_list, pokouxingshi_list, hanjiefangfa_list, [], [], jiancefangfa_list, hegejibie_list]];//选项
function OnClickPlus(cardIndex) {//按下加号键的操作
    table[cardIndex].children[1].removeChild(table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1]);
    var tr = document.createElement("tr");
    for (var i = 0; i < type[0].length; i++) {//产生一堆输入框
        var td = document.createElement("td");
        if (type[cardIndex][i] === 0) {
            var input = document.createElement("input");
            input.setAttribute("type", "text");
            input.setAttribute("onkeyup", "OnKeyUp(" + i + ", " + cardIndex + ")");
            input.setAttribute("size", "6");
            input.setAttribute("style", "border-radius: 5px");
            if (table[cardIndex].children[1].childElementCount > 0) {//复制上一行的数据
                input.value = table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1].children[i].innerHTML;
            }
            td.appendChild(input);
            tr.appendChild(td);
        } else {
            var select = document.createElement("select");
            for (var j = 0; j < selection[cardIndex][i].length; j++) {
                var selectValue = document.createElement("option");
                selectValue.setAttribute("value", selection[cardIndex][i][j]);
                selectValue.innerHTML = selection[cardIndex][i][j];
                select.setAttribute("style", "border-radius: 5px");
                select.appendChild(selectValue);
            }
            if (table[cardIndex].children[1].childElementCount > 0) {//复制上一行的数据
                $(select).val(table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1].children[i].innerHTML);
            }
            td.appendChild(select);
            tr.appendChild(td);
        }
    }
    td = document.createElement("td");
    var confirmButton = document.createElement("button");
    confirmButton.setAttribute("class", "btn btn-xs btn-success");
    confirmButton.setAttribute("onclick", "OnClickConfirm(" + cardIndex + ")");
    var confirmIcon = document.createElement("i");
    confirmIcon.setAttribute("class", "ace-icon fa fa-check bigger-120");
    confirmButton.appendChild(confirmIcon);
    td.appendChild(confirmButton);
    tr.appendChild(td);
    table[cardIndex].children[1].appendChild(tr);
}

function OnKeyUp(index, cardIndex) {//添加键盘操作，只有按下回车键才有效
    if (event.keyCode === 13) {
        if (index + 1 < type[0].length)
            event.target.parentNode.parentNode.children[index + 1].children[0].focus();
        else
            OnClickConfirm();
    }
}

function OnClickConfirm(cardIndex) {//按下确认键或者在最后一个输入框按下回车键的操作
    var inputText = [];
    for (i = 0; i < type[0].length; i++) {//提取所有输入值
        if (type[cardIndex][i] === 0)
            inputText[i] = table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1].children[i].children[0].value;
        else {
            var selected = table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1].children[i].children[0];
            inputText[i] = selected.options[selected.selectedIndex].text;
        }
    }
    table[cardIndex].children[1].removeChild(table[cardIndex].children[1].children[table[cardIndex].children[1].childElementCount - 1]);
    var tr = document.createElement("tr");
    for (var i = 0; i < type[0].length; i++) {//删除输入框，替换为文本框
        var td = document.createElement("td");
        td.innerHTML = inputText[i];
        tr.appendChild(td);
    }
    td = document.createElement("td");//添加一个处理按钮
    td.innerHTML = "<button class=\"btn btn-xs btn-success\" onclick=\"OnClickDelete()\"><i class=\"ace-icon fa fa-minus bigger-120\" ></i></button>";
    tr.appendChild(td);
    table[cardIndex].children[1].appendChild(tr);
    tr = document.createElement("tr");//添加新行，并且在最后加一个加号按钮
    tr.innerHTML = "<td/><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/><td/><td><button class=\"btn btn-xs btn-success\" onclick=\"OnClickPlus(" + cardIndex + ")\"><i class=\"ace-icon fa fa-plus bigger-120\"></i></button></td>";
    table[cardIndex].children[1].appendChild(tr);
    console.log(GetInputs(cardIndex));
    // console.log(cardIndex)
}

function OnClickDelete() {
    var target = event.target;
    while (target.childElementCount !== 0) target = target.children[0];
    target.parentNode.parentNode.parentNode.parentNode.removeChild(target.parentNode.parentNode.parentNode);
}

function GetInputs(cardIndex) {//获取所有输入数据
    var values = [[]];
    for (var i = 0; i < table[cardIndex].children[1].childElementCount - 1; i++) {
        for (var j = 0; j < type[0].length; j++) {
            if (values[j] === undefined) values[j] = [];
            values[j][i] = table[cardIndex].children[1].children[i].children[j].innerHTML;
        }
    }
    return values;
}

//动态列表结束

//委托单基本信息表所需要的信息
var taskTableData = {};
var workpieceTableData = {};
var workcountTableData = {};
//委托编号，提交完基本信息后，若成功才能拿到
var w_tid;
//提交委托 按钮
$('#commitDeputeBtn').click(function () {
    let inputs = GetInputs(0);
    let date = new Date();
    var sentMessage = {
        "task_description": document.getElementById("task_description").value,
        "task_pid": projectID,
        "task_pname": projectName,
        "task_pdid": document.getElementById("task_pdid").value,
        "task_product": document.getElementById("task_product").value,
        "task_workNum": inputs[0].length,
        "task_opportunity": document.getElementById("task_opportunity").value,
        "task_addr": document.getElementById("task_addr").value,
        "task_standard": document.getElementById("task_standard").value,
        "task_heat": document.getElementById("task_heat").value,
        "task_position": document.getElementById("task_position").value,
        "task_phone": user.user_account,
        "task_start": date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),//委托时间
        "task_type": document.getElementById("task_type").value,
        "task_company": document.getElementById("task_company").value,
        "task_uid": user.user_id,
        "task_level": document.getElementById("task_level").value,
        "task_check": document.getElementById("task_check").value,
        "task_time": document.getElementById("task_time").value,
        "requestType": "commitTaskTable"
    };
    var postData;
    $.ajax({
        url: '/task/newDepute',
        type: 'post',
        data: sentMessage,
        async: false,
        success: function (data, status) {
            if (status == 'success') {
                postData = data;
                console.log(data);
            }
        },
        error: function (data, status) {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });

    sentMessage = {
        'w_pid': projectID, //项目编号
        'w_tid': postData.insertId,  //委托编号
        'w_pipeName': inputs[2], //部件/管线名称
        'w_pipeNum': inputs[0], //部件/管线编号
        'w_weldNum': inputs[1],    //工件/焊缝编号
        'w_spec': inputs[6],   //工件规格
        'w_texture': inputs[7],    //材质
        'w_scale': inputs[3],  //检测比例
        'w_weldM': inputs[9],  //焊接方法
        'w_test': inputs[12],   //检验方法
        'w_qua': inputs[13],    //合格级别
        'w_weldPer': inputs[10],
        'w_weldTime': inputs[11],  //焊接时间
        'w_type': inputs[8],     //坡口形式
        'w_photoNum': inputs[5],
        'w_re': inputs[4],
        'requestType': 'commitWorkpieceTable',
        'num': inputs[0].length
    };
    console.log(sentMessage.w_pipeName);
    $.ajax({
        url: '/task/newDepute',
        type: 'post',
        data: sentMessage,
        async: false,
        traditional: true,
        success: function (data, status) {
            if (status == 'success') {
                console.log("工件");
            }
        },
        error: function (data, status) {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });
    $.ajax({
        url: '/task/newDepute',
        type: 'post',
        data: {
            'w_tid': postData.insertId,
            'requestType': 'commitWorkCountTable'
        },
        async: false,
        success: function (data, status) {
            if (status == 'success') {
            }
        },
        error: function (data, status) {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });
    $.ajax({
        url: '/task/newDepute',
        type: 'post',
        data: {
            'w_tid': postData.insertId,
            'requestType': 'updateWCIdInWorkPiece'
        },
        async: false,
        success: function (data, status) {
            if (status == 'success') {
                alert("提交成功");
                history.back();
            }
        },
        error: function (data, status) {
            if (status == 'error') {
                alert("你的网络有问题！");
            }
        }
    });
});

//检查委托单的基本信息是否完整，即数据库中的task表
//符合要求返回true，否则设置警示消息，并返回false
//校验功能还没做，只将数据拿了出来
function checkBaseInfo() {
    //委托单位
    var task_company = $('#weituodanwei').val();
    //委托说明
    var task_description = $('#weituoshuoming').val();
    //委托单中工件数量
    var task_workNum = inputs.length;
    //项目名称
    var task_pname = projectName;
    //项目编号
    var task_pid = GetQueryString('pId');
    //产品名称
    var task_product = $('#chanpinmingcheng').val();
    //检测时机
    var task_state = $('#jianceshiji').val();
    //检测地点
    var task_addr = $('#jiancedidian').val();
    //委托人
    var task_client = user.user_name;
    //联系电话
    var task_phone = user.user_account;
    //检测标准
    var temp1 = document.getElementById('jiancebiaozhun');
    var index1 = temp1.selectedIndex;
    var task_standard = temp1.options[index1].value;
    //坡口形式
    var task_tid = $('#changpinbianhao').val();
    //热处理状态
    var msg1 = document.getElementById('rechuli');
    var index2 = msg1.selectedIndex;
    var task_heat = msg1.options[index2].value;
    //检测部位
    var task_position = $('#jiancebuwei').val();

    taskTableData = {
        'requestType': 'commitTaskTable',
        'task_company': task_company,
        'task_description': task_description,
        'task_workNum': task_workNum,
        'task_pid': task_pid,
        'task_pname': task_pname,
        'task_product': task_product,
        'task_state': task_state,
        'task_addr': task_addr,
        'task_client': task_client,
        'task_phone': task_phone,
        'task_standard': task_standard,
        'task_tid': task_tid,
        'task_heat': task_heat,
        'task_position': task_position

    };
    return true;
}